#!/usr/bin/python

_Copyright = "Copyright @ 2010 Michael P. Reilly. All rights reserved."

_SCM_ID = "$Id: tools.py 86 2010-12-17 03:30:13Z arcege@gmail.com $"

import logging
import md5
import urllib2
import urlparse
from google.appengine.api import urlfetch

__all__ = [
  'send_admin_mail',
  'update_image_md5',
  'valid_name',
]

def valid_name(name, invalidchars='/, \t\n:'):
    for c in name:
        if c in invalidchars:
            return False
    else:
        return True

def update_image_md5(image, baseurl, force=False):
    if image.md5 and not force:
        return
    sum = md5.new()
    try:
        nurl = '/images/secicon/%s.png' % image.iname
        url = urlparse.urljoin(baseurl, nurl)
        parts = urlparse.urlparse(url)
        if parts[0] == 'https':
            parts[0] == 'http'
            url = urlparse.urlunparse(parts)
        logging.warn('retrieving %s' % repr(url))
        result = urlfetch.fetch(url)
        if result.status_code == 200:
            sum.update(result.content)
    except urllib2.URLError, e:
        raise ValueError(str(e))
    if image.md5 != sum.hexdigest():
        image.md5 = sum.hexdigest()
        image.put()

def send_admin_mail(subject, body,
        fromaddr='keycustodian.admin@gmail.com',
        adminaddrs=['arcege@gmail.com']):
    from google.appengine.api import mail
    mail.send_mail(
        sender=fromaddr,
        to=','.join(adminaddrs),
        subject=subject,
        body=body
    )

